
import { invoke } from '@tauri-apps/api/core';
import { ComparsionOperator, DeleteCondition, DeleteOptions, QueryCondition, QueryExtention, QueryOptions, UpdateCondition, UpdateOptions } from '../types';
import optionsWrap from '@/components/datasets/create/website/base/options-wrap';
import { DataSource } from '@/services/data-source';
import { createDirs, getNowFormatDate, homePath, saveText, uuid } from '@/utils';
import { create, remove } from '@tauri-apps/plugin-fs';
import { dsDelete, dsFindOne, dsInsert } from '../datasource';
import { PROJECT_APPLICATION_CLASS_IDENTIFIER } from '@/services/constants';
import { appCreateEmptyAgent } from './agent';
import { qiniuUploadLocalFile } from '@/services/rrg01';
import { fileCompressDir, fileUnzip } from '@/services/peer';
import { UploadFile } from 'antd';
import { execute } from '@/services/connector';
import { APPLICATION_INIT_SQL } from './init-sql';

export enum ProjectApplicationType {
    Agent = 'agent',
    G01Server = 'g01server',
    ChatFlow = 'chatflow',
    CustomH5 = 'custom_h5',
}

export const PROJECT_APPLICATION_TYPE_SELECT_OPTIONS = [
    { value: 'agent', label: 'AI Agent' },
    { value: 'g01server', label: 'G01服务端' },
    { value: 'chatflow', label: '工作流' },
    { value: 'custom_h5', label: '自定义H5' },
];


export const projectApplicationTypeLabelToString = (at: ProjectApplicationType) => {
    switch (at) {
        case ProjectApplicationType.Agent:
            return "AI Agent";
        case ProjectApplicationType.G01Server:
            return "G01服务端";
        case ProjectApplicationType.ChatFlow:
            return "工作流";
        case ProjectApplicationType.CustomH5:
            return "自定义H5";
    }
    return "其他";
}

export interface InstalledApplication {
    id?: number;
    project_identifier?: string;
    identifier: string;
    name: string;
    title?: string;
    icon: string;
    application_type: ProjectApplicationType;
    version: string;
    main?: string;
    installed_path: string;
    installed_at: number;
    description?: string;
    created_at?: number;
    updated_at?: number;
}

export interface ProjectApplication {
    id?: number;
    project_identifier: string;
    identifier: string;
    name: string;
    title: string;
    icon: string;
    application_type: ProjectApplicationType;
    workflow_identifier: number;
    path: string;
    datasource: string;
    description: string;
    created_at: number;
    updated_at: number;
}

export const appDatasource = async (identifier: string, isInstalled: boolean): Promise<DataSource | null> => {

    console.log(identifier, isInstalled);

    let res: any = await invoke('plugin:mg-platform|app_datasource', {
        identifier: identifier,
        isInstalled: isInstalled,
    });
    console.log(res);
    return res;
}

export const appCreateEmptyApplication = async (value: ProjectApplication): Promise<any> => {

    if (value.application_type === ProjectApplicationType.Agent) {
        let res = await appCreateEmptyAgent(value)
    }

    //
    let datasource = '';
    let applicationIdentifier = value.identifier;
    try {
        // 新建应用数据库
        let home = await homePath();
        let exportPath = `${home}/projects/${value.project_identifier}/${applicationIdentifier}/`;
        await createDirs(exportPath);
        datasource = `${exportPath}/system.sqlite`;
        await create(datasource);
        //执行初始化sql
        await execute({ id: 0, protocol: 'sqlite', url: `sqlite:${datasource}`, database_type: 'sqlite' }, APPLICATION_INIT_SQL, [], {});
    } catch (err) {
        console.error(err);
    }
    //插入project applications
    console.log({
        ...value,
        datasource: datasource,
    });
    try {
        let wres = await dsInsert(0, PROJECT_APPLICATION_CLASS_IDENTIFIER, {
            ...value,
            datasource: datasource,
        });
    } catch (err) {
        console.error(err);
    }
    return
}


export const appRemoveProjectApplication = async (applicationIdentifier: string) => {

    //相关的文件删除
    try {
        //获取到相关的文件信息
        let application = await dsFindOne(0, PROJECT_APPLICATION_CLASS_IDENTIFIER, {
            attributes: [{
                name: 'identifier',
                operator: ComparsionOperator.Equal,
                value: applicationIdentifier
            }]
        });

        if (application) {
            //

        }
    } catch (err) {
        console.log(err);
    }

    await dsDelete(0, PROJECT_APPLICATION_CLASS_IDENTIFIER, {
        attributes: [{
            name: 'identifier',
            operator: ComparsionOperator.Equal,
            value: applicationIdentifier
        }]
    });
}

export const appUpdateApplicationFiles = async (projectIdentifier: string, applicationIdentifier: string, file: UploadFile): Promise<string> => {
    let home = await homePath();

    //
    let exportPath = `${home}/projects/${projectIdentifier}/${applicationIdentifier}/content`;
    //先清空
    remove(exportPath, { recursive: true });

    let zipFile = file.response.path;
    console.log(file, file.response.path);
    //
    await fileUnzip(zipFile, exportPath);
    return exportPath;
}



export const appUploadProjectApplication = async (application: ProjectApplication): Promise<string> => {
    console.log('appication:', application);
    let home = await homePath();
    let exportId = uuid();
    let file = `${home}/temp/${exportId}.zip`;
    try {
        //打包文件
        application.path;
        application.datasource;
        //file_compress_dir
        let exportPath = `${home}/projects/${application.project_identifier}/${application.identifier}/`;
        let compressRes = await fileCompressDir(exportPath, file);
        console.log(compressRes);
        //上传文件
        let uploadResult = await qiniuUploadLocalFile(file, `g01/share/images/applications/${getNowFormatDate('')}`);
        console.log(uploadResult);
        return uploadResult.key;
    } catch (err) {
        console.log(err);
    }
    //
    return "";
}


export default {}